import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './vuex'
import i18n from './i18n/i18n.js'
import './plugins/element.js'

Vue.config.productionTip = false;

//  获取角色信息，根据用户权限动态加载路由
router.beforeEach((to, from, next) => {
    console.log(store.getters.token);
    // debugger

    if (store.getters.token) {
        store.dispatch('setToken', store.getters.token);
        if (to.path === '/login') {
            next({path: '/home'})
        } else {
            if (!store.getters.info.role) {
                // const role = ['/markdown', '/erji', '/erji2', '/siji', '/wuji']
                !async function getAddRouters() {
                    await store.dispatch('getInfo', store.getters.token);
                    await store.dispatch('newRoutes', store.getters.info.role);
                    console.log(store.getters.addRouters);
                    await router.addRoutes(store.getters.addRouters);
                    next({path: '/index'})
                }()
            } else {
                let is404 = to.matched.some(record => {
                    if (record.meta.role) {
                        return record.meta.role.indexOf(store.getters.info.role) === -1
                    }
                })
                if (is404) {
                    next({path: '/404'});
                    return false
                }
                next()
            }
        }
    } else {
        if (to.path === '/login') {
            next()
        }
        next({path: '/login'})

    }
})

new Vue({
    router,
    store,
    i18n,
    render: h => h(App)
}).$mount('#app');
